package com.jimmy.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jimmy.reggie.common.R;
import com.jimmy.reggie.entity.Category;
import com.jimmy.reggie.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    @PostMapping
    public R<String> addCategory(@RequestBody Category category){
        if (categoryService.save(category)){
            return R.success("添加成功");
        }
        return R.error("未知错误");
    }

    @GetMapping("/page")
    public R<Page> page(int page,int pageSize){
        Page<Category> categoryPage = new Page<>(page, pageSize);
        LambdaQueryWrapper<Category> categoryLambdaQueryWrapper = new LambdaQueryWrapper<>();
        //添加排序条件
        categoryLambdaQueryWrapper.orderByDesc(Category::getSort);
        //调用service开始查询
        categoryService.page(categoryPage, categoryLambdaQueryWrapper);
        return R.success(categoryPage);
    }

    @DeleteMapping
    public R<String> deleteCategory(Long id){
        log.info("删除处理中");
        if (categoryService.removeById(id)){
            return R.success("删除成功");
        }
        return R.error("未知错误");
    }

    @PutMapping
    public R<String> updateCategory(@RequestBody Category category){
        log.info("来了哈，开始更新了老弟");
        if (categoryService.updateById(category)){
            return R.success("删除成功");
        }
        return R.error("未知错误");
    }

    @GetMapping("/list")
    public R<List<Category>> list(Category category){
        LambdaQueryWrapper<Category> categoryQurey = new LambdaQueryWrapper<>();
        categoryQurey.eq(category.getType()!=null,Category::getType,category.getType());
        categoryQurey.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);
        List<Category> list = categoryService.list(categoryQurey);
        return R.success(list);
    }

}
